package com.infinova.datax.apireader;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bigbird-0101
 * @date 2023-08-01 10:00
 */
public class Segment {
    private Long index;
    private Integer requestCount;

    public Segment() {
    }

    public Segment(Long index, Integer requestCount) {
        this.index = index;
        this.requestCount = requestCount;
    }

    public Long getIndex() {
        return index;
    }

    public void setIndex(Long index) {
        this.index = index;
    }

    public Integer getRequestCount() {
        return requestCount;
    }

    public void setRequestCount(Integer requestCount) {
        this.requestCount = requestCount;
    }

    @Override
    public String toString() {
        return "Segment{" +
                "index=" + index +
                ", requestCount=" + requestCount +
                '}';
    }

    public static List<Segment> split(int maxRequestCount, int segmentCount, long baseIndex, int indexAddBatchCount){
        // 每段的商
        int quotient = maxRequestCount / segmentCount;
        // 每段的余数
        int remainder = maxRequestCount % segmentCount;
        List<Segment> segmentList=new ArrayList<>();
        // 将商均匀分配到每段
        for (int i = 0; i < segmentCount; i++) {
            Segment segment=new Segment();
            segment.requestCount=quotient;
            segmentList.add(segment);
            if(0==remainder){
                if(i==0) {
                    segment.index=baseIndex;
                }else{
                    Segment preSegment = segmentList.get(i - 1);
                    segment.index=preSegment.index+ (long) (preSegment.requestCount) *indexAddBatchCount;
                }
            }
        }
        // 将余数依次分配到每段
        for (int i = 0; i < remainder; i++) {
            Segment segment = segmentList.get(i);
            segment.requestCount = segment.requestCount + 1;
            if(i==0) {
                segment.index=baseIndex;
            }else{
                Segment preSegment = segmentList.get(i - 1);
                segment.index=preSegment.index+ (long) (preSegment.requestCount) *indexAddBatchCount;
            }
        }
        if(0!=remainder&&remainder<segmentCount){
            for(int i=remainder;i<segmentCount;i++){
                Segment segment = segmentList.get(i);
                Segment preSegment = segmentList.get(i - 1);
                segment.index=preSegment.index+ (long) (preSegment.requestCount + 1) *indexAddBatchCount;
            }
        }
        return segmentList;
    }
}
